package ai4games_tests.maths;

import game2dai.maths.Geometry2D;
import processing.core.PApplet;

public class BoxBoxIntersect extends PApplet {

	final int IRAD = 5;
	float ax0, ay0, ax1, ay1, bx0, by0, bx1, by1;
	float bw = 50, bh = 30;

	float[] ipoint = null;
	boolean intersect;

	public void setup(){
		size(400,300);
		cursor(CROSS);
		float cx = width/2;
		float cy = height/2;
		float w = 0.15f * width;
		float h = 0.15f * height;
		ax0 = cx - w;
		ay0 = cy - h;
		ax1 = cx + w;
		ay1 = cy + h;

		intersect = false;
		rectMode(CORNERS);
	}

	public void draw(){
		background(128);
		bx0 = mouseX - bw;
		by0 = mouseY - bh;
		bx1 = mouseX + bw;
		by1 = mouseY + bh;


		intersect = Geometry2D.box_box(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1);
		ipoint = makeFloatArray(Geometry2D.box_box_p(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1));
		strokeWeight(1.1f);
		stroke(0,255,0);
		fill(255,255,192,140);
		if(intersect)
			stroke(255,0,0);
		rect(ax0, ay0, ax1, ay1);
		rect(bx0, by0, bx1, by1);


		fill(200,200,255);
		noStroke();
		for(int p = 0; p < ipoint.length; p += 2)
			ellipse((float)ipoint[p], (float)ipoint[p+1], IRAD,IRAD);

		fill(255,255,0);
		text("Number of intersections = " + ipoint.length/2, 10, height - 4);
	}

	public float[] makeFloatArray(double[] da){
		float[] fa = new float[da.length];
		for(int i = 0; i < fa.length; i++)
			fa[i] = (float)da[i];
		return fa;
	}

	public void test(){
		float cirLocx = 100;
		float cirLocy = 100;
		float cirSize = 50;
		float cirHalfSize = cirSize * 0.5f;
		if (mouseX >= cirLocx - cirSize * .5 && mouseX <= cirLocx + cirSize * .5 && mouseY >= cirLocy - cirSize * .5 && mouseY <= cirLocy + cirSize * .5){
			test();
		}
		if (mouseX >= cirLocx - cirHalfSize && mouseX <= cirLocx + cirHalfSize && mouseY >= cirLocy - cirHalfSize && mouseY <= cirLocy + cirHalfSize){
			test();
		}
	}
	
	public boolean isOverSquare(float x, float y, float cx, float cy, float size){
		float hsize = size * 0.5f;
		return (x >= cx - hsize && x <= cx + hsize && y >= cy - hsize && y <= cy + hsize );
	}
}
